import React from 'react';
import { DatePicker,Button,List ,DatePickerView, Icon} from 'weaver-mobile';
import moment from 'moment';
export default class WeekDatePicker extends React.Component {
  static defaultProps = {
    prefixCls: 'workplan-week-datepicker'
  }
  constructor(props) {
    super(props);
    this.state = {
      date: props.value,
      dateRange: `${props.startDate} ~ ${props.endDate}` || moment(new Date()).format('YYYY-MM-DD'),
      visible: props.visible
    }
    this.onOk = this.onOk.bind(this);
    this.onDismiss = this.onDismiss.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    let nextDateRange = `${nextProps.startDate} ~ ${nextProps.endDate}`;
    this.setState({
      dateRange: nextDateRange
    });
  }

  onOk = (date) => {
    if (!date) date = new Date();
    let dateCopy = moment(date).format('YYYY-MM-DD');
    this.setState({
      date: date,
      visible: false
    });
    if (!this.props.onOk) return;
    this.props.onOk(dateCopy);
  }

  onChange = (diff) => {
    let current = this.state.date === '' ? moment() : moment(this.state.date);
    let dayOfYear = current.dayOfYear();
    current.dayOfYear(dayOfYear + diff*7);
    if(typeof diff === 'string' && diff.indexOf('-') > -1) {
      current = moment(diff);
    }
    this.setState({
      date: current.format('YYYY-MM-DD'),
    });
    if (!this.props.onChange) return;
    this.props.onChange(current.format('YYYY-MM-DD'));
  }

  onDismiss = () => {
    this.setState({
      visible: false
    });
  }

  render() {
    const { prefixCls } = this.props;
    const { date, dateRange, visible } = this.state;
    let pickerProps = {
      mode: 'date',
      visible: visible,
      value: date,
      onOk: this.onOk,
      onDismiss: this.onDismiss,
      onChange: this.onChange
    };
    return (
      <div>
        <div className={`${prefixCls}`}>
          <span className={`${prefixCls}-icon`}>
            <Icon type={'arrow-left'} size='xs' onClick={() => {this.onChange(-1)}} />
          </span>
          <div className={`${prefixCls}-content`} onClick={() => this.setState({visible: true})}>
            <span className={'week-range'}>
              {dateRange}
            </span>
          </div>
        <div className={`${prefixCls}-picker`}>
          <DatePicker {...pickerProps}/>
        </div>
          <span className={`${prefixCls}-icon`}>
            <Icon type={'arrow-right'}  size='xs' onClick={() => {this.onChange(1)}}/>
          </span>
        </div>
      </div>
    )
  }
}
